package com.java.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class ImageUtils {

    public static boolean isJpgOrPng(String filename) {
        String name = filename.toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png");
    }

    /**
     * 校验 & 压缩大于1MB的图片
     * 返回可直接上传微信的 File
     */
    public static File handleAndMaybeCompress(MultipartFile multipartFile) throws IOException {
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new IllegalArgumentException("未上传文件或文件为空");
        }
        String originalName = multipartFile.getOriginalFilename();
        if (!isJpgOrPng(originalName)) {
            throw new IllegalArgumentException("只支持jpg/png图片");
        }

        // 保存为临时文件
        File origin = File.createTempFile("wximg_raw", "." + getFileSuffix(originalName));
        multipartFile.transferTo(origin);

        final long MAX_SIZE = 1024 * 1024;

        if (origin.length() <= MAX_SIZE) {
            return origin;
        }
        // 循环压缩
        File compressed = File.createTempFile("wximg_compress", "." + getFileSuffix(originalName));
        float quality = 0.95f;
        while (true) {
            Thumbnails.of(origin)
                    .scale(1f)
                    .outputQuality(quality)
                    .toFile(compressed);
            if (compressed.length() <= MAX_SIZE || quality <= 0.20f) {
                break;
            }
            quality -= 0.05f;
        }
        origin.delete(); // 只留最终文件
        return compressed;
    }

    private static String getFileSuffix(String filename) {
        int i = filename.lastIndexOf(".");
        if (i > 0) {
            return filename.substring(i + 1).toLowerCase();
        }
        return "";
    }
}